/***********************************************************************************
Copy right:	    hqyj Tech.
Author:         jiaoyue
Date:           2023.07.01
Description:    http请求处理
***********************************************************************************/

#include <sys/types.h>
#include <sys/socket.h>
#include "custom_handle.h"
#include "shmem.h"
#include "msg_queue_peer.h"
#include "cJSON.h"
#include <sqlite3.h>
#define KB 1024
#define HTML_SIZE (64 * KB)

//普通的文本回复需要增加html头部
#define HTML_HEAD "Content-Type: text/html\r\n" \
                  "Connection: close\r\n"

static int handle_login(int sock, const char *input)
{
    char reply_buf[HTML_SIZE] = {0};
    char *uname = strstr(input, "username=");
    uname += strlen("username=");
    char *p = strstr(input, "password");
    *(p - 1) = '\0';
    printf("username = %s\n", uname);
    char *passwd = p + strlen("password=");
    printf("passwd = %s\n", passwd);

    if (strcmp(uname, "admin") == 0 && strcmp(passwd, "admin") == 0)
    {
        sprintf(reply_buf, "%s login", uname);
        send(sock, reply_buf, strlen(reply_buf), 0);
    }
    else
    {
        printf("web login failed\n");
        //"用户名或密码错误"提示，chrome浏览器直接输送utf-8字符流乱码，没有找到太好解决方案，先过渡
        // char out[128] = {0xd3,0xc3,0xbb,0xa7,0xc3,0xfb,0xbb,0xf2,0xc3,0xdc,0xc2,0xeb,0xb4,0xed,0xce,0xf3};
        sprintf(reply_buf, "用户名或密码错误");

        send(sock, reply_buf, strlen(reply_buf), 0);
    }

    return 0;
}

static int handle_getdata(int sock, const char *query_string)
{
    // printf("val更新\n");
    char reply_buf[HTML_SIZE] = {0};
    strcpy(reply_buf, shm_get_data());
    send(sock, reply_buf, strlen(reply_buf), 0);
    return 0;
}
static int handle_gethis(int sock, const char *query_string)
{
    // printf("val更新\n");
    char reply_buf[HTML_SIZE] = {0};
    char sql[1024] = {0};
    char **result = NULL, **result2 = NULL;
    int row, column, k = 2, row2, column2;
    sqlite3 *db; //打开数据库
    if (sqlite3_open("/home/hq/24011/project/gateway-program-/daterreport/datahistory.db", &db) != SQLITE_OK)
    {
        fprintf(stderr, "open datahistory err %s", sqlite3_errmsg(db));
        return -1;
    }
    char *errmsg = NULL; //数据库错误信息
    strcpy(sql, "SELECT * FROM HUMIDITY ORDER BY TIME DESC");
    sqlite3_get_table(db, sql, &result, &row, &column, &errmsg);
    printf("row:%d column:%d\n", row, column);
    strcpy(sql, "SELECT * FROM TEMPERATURE ORDER BY TIME DESC");
    sqlite3_get_table(db, sql, &result2, &row2, &column2, &errmsg);
    // printf("row:%d column:%d\n", row, column);
    //humi
    cJSON *root = cJSON_CreateObject();
    cJSON *data = cJSON_CreateArray();
    cJSON_AddItemToObject(root, "data", data);
    for (int i = 1; i < 2; i++)
    {
        cJSON *item = cJSON_CreateObject();
        for (int j = 0; j < column; j++)
        {
            // printf("%s ",result[k++]);

            if (j == 0)
            {
                cJSON *time = cJSON_CreateNumber(atol(result[k]));
                cJSON_AddItemToObject(item, "time", time);
            }
            else
            {
                cJSON *humi = cJSON_CreateNumber(atof(result[k]));
                cJSON_AddItemToObject(item, "humi", humi);
                cJSON *temp = cJSON_CreateNumber(atof(result[k]));
                    cJSON_AddItemToObject(item, "temp", temp);
            }
            // strcat(reply_buf, result[i][j]);
            // strcat(reply_buf, ",");
            k++;
        }

        cJSON_AddItemToArray(data, item);
    }

    char *p = cJSON_Print(root);
    printf("%s\n", p);
    sprintf(reply_buf, "%s", p);
    send(sock, reply_buf, strlen(reply_buf), 0);

    // //
    // strcpy(sql,"SELECT * FROM TEMPERATURE ORDER BY TIME DESC");//
    // send(sock, reply_buf, strlen(reply_buf), 0);
    return 0;
}
int msg_setdata(int sock, const char *input)
{

    // 构建要回复的JSON数据
    const char *json_response = "{\"message\": \"Hello, client!\"}";
    // 发送HTTP响应给客户端
    send(sock, json_response, strlen(json_response), 0);
    cJSON *root = cJSON_Parse(input);
    cJSON *key = cJSON_GetObjectItem(root, "key");
    cJSON *value = cJSON_GetObjectItem(root, "value");
    msg m;

    if (key->valueint > 300) //stm32
    {
        m.type = 1;
    }
    else if (key->valueint > 100)
    {
        m.type = 2;
    }
    m.key = key->valueint;
    if (value->type == cJSON_String)
    {
        strcpy(m.val, value->valuestring);
    }
    else
    {
        sprintf(m.val, "%d", value->valueint);
    }
    printf("key:%d\n",m.key);
    msg_queue_send("msgqueue", &m, sizeof(msg), 0);
}
/**
 * @brief 处理自定义请求，在这里添加进程通信
 * @param input
 * @return
 */
int parse_and_process(int sock, const char *query_string, const char *input)
{
    //query_string不一定能用的到
    //先处理登录操作

    if (query_string != NULL)
    {
        if (strstr(query_string, "username=") && strstr(query_string, "password="))
        {
            return handle_login(sock, query_string);
        }
        else if (strstr(query_string, "getdata"))
        {
            return handle_getdata(sock, query_string);
        }
        else if (strstr(query_string, "gethistory"))
        {
            return handle_gethis(sock, query_string);
        }
    }
    //处理从共享内存拿数据，上传到web显示
    else //剩下的都是json请求，这个和协议有关了
    {
        //控制写消息队列
        msg_setdata(sock, input);
    };
    return 0;
}
